// import static java.lang.StringTemplate.STR;

// 编译: javac -source 21 --enable-preview BenchStringTemplate.java
// 运行: java --enable-preview BenchStringTemplate
public class BenchStringTemplate {
	static final int TEST_COUNT = 1_000_0000; // 测试循环次数

	// 直接用字符串拼接法
	static void benchConcat() {
		int h = 0;
		var t = System.nanoTime();
		for (int i = 0; i < TEST_COUNT; i++) {
			var s = "abcde " + i + " opq " + -i + " xyz";
			h += s.hashCode(); // 计算并累加字符串hash值最后输出,避免被无效优化掉
		}
		System.out.println("benchConcat:   " + h + ", " + (System.nanoTime() - t) + " ns");
	}

	// 使用StringBuilder的append方式拼接
	static void benchAppend() {
		int h = 0;
		var t = System.nanoTime();
		for (int i = 0; i < TEST_COUNT; i++) {
			//noinspection StringBufferReplaceableByString
			var sb = new StringBuilder().append("abcde ").append(i).append(" opq ").append(-i).append(" xyz");
			h += sb.toString().hashCode();
		}
		System.out.println("benchAppend:   " + h + ", " + (System.nanoTime() - t) + " ns");
	}

	// 使用预设足够大空间的StringBuilder再append的方式拼接
	static void benchAppend2() {
		int h = 0;
		var t = System.nanoTime();
		for (int i = 0; i < TEST_COUNT; i++) {
			//noinspection StringBufferReplaceableByString
			var sb = new StringBuilder(28).append("abcde ").append(i).append(" opq ").append(-i).append(" xyz");
			h += sb.toString().hashCode();
		}
		System.out.println("benchAppend2:  " + h + ", " + (System.nanoTime() - t) + " ns");
	}

	// 使用String的join方法拼接
	static void benchJoin() {
		int h = 0;
		var t = System.nanoTime();
		for (int i = 0; i < TEST_COUNT; i++) {
			var s = String.join("", "abcde ", String.valueOf(i), " opq ", String.valueOf(-i), " xyz");
			h += s.hashCode();
		}
		System.out.println("benchJoin:     " + h + ", " + (System.nanoTime() - t) + " ns");
	}

/*
	// 使用JDK21预览的字符串模板拼接
	static void benchTemplate() {
		int h = 0;
		var t = System.nanoTime();
		for (int i = 0; i < TEST_COUNT; i++) {
			var s = STR. "abcde \{ i } opq \{ -i } xyz" ;
			h += s.hashCode();
		}
		System.out.println("benchTemplate: " + h + ", " + (System.nanoTime() - t) + " ns");
	}
*/

	public static void main(String[] args) {
		for (int i = 0; i < 5; i++) { // 测试5轮,充分预热,最后一轮的成绩能代表最终优化的效果
			System.out.println("--- Benchmark " + i + " ---");
			benchConcat();
			benchAppend();
			benchAppend2();
			benchJoin();
//			benchTemplate();
		}
	}
}
/*
--- Benchmark 4 ---
benchConcat:   2094814309, 32120900 ns
benchAppend:   2094814309, 37187800 ns
benchAppend2:  2094814309, 34386300 ns
benchJoin:     2094814309, 91091300 ns
benchTemplate: 2094814309, 33453400 ns
*/
